import { Form, Input, Modal } from 'antd';
import React, { useEffect, useState } from 'react';

import { message } from '@/App';
import { createCat, updateCat } from '@/api/books';
import { ICat } from '@/models/Cat';

interface IProps {
  cat?: ICat;
  open: boolean;
  setOpen: (open: boolean) => void;
  onConfirm: () => void;
}

const CreateCatDialog = (props: IProps) => {
  const { cat, open, setOpen, onConfirm } = props;
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (cat) {
      form.setFieldsValue(cat);
    }
  }, [cat, form]);

  const onOk = () => {
    form.submit();
  };

  const onCancel = () => {
    setOpen(false);
  };

  const onFinish = async (values: any) => {
    setLoading(true);
    const handler = cat ? updateCat : createCat;
    await handler({
      id: cat?.id,
      ...values,
    });
    message.info(cat ? '更新成功' : '创建成功');
    onConfirm();
    setOpen(false);
    setLoading(false);
  };

  return (
    <Modal
      title={cat ? '更新猫咪' : '创建猫咪'}
      open={open}
      onOk={onOk}
      onCancel={onCancel}
      confirmLoading={loading}
    >
      <Form form={form} onFinish={onFinish}>
        <Form.Item name="name" label="姓名" rules={[{ required: true }]}>
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item name="description" label="描述" rules={[{ required: true }]}>
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item name="type" label="类别" rules={[{ required: true }]}>
          <Input placeholder="请输入" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateCatDialog;
